<script setup>
import { reactive, ref, defineProps, defineEmits, onMounted, watch } from 'vue'
import { roleSubmit } from '@/api';
import { ElMessage } from 'element-plus'

const emits = defineEmits(['closed'])

const props = defineProps({
  isShowForm: Boolean,
  action: String,
  roleItem: Object,
})

const roleForm = ref()
const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 10, message: '角色名称最少2位, 最多10位', trigger: 'blur' },
  ]
}

const state = reactive({
  roleForm: {
    roleName: '',
    remark: ''
  },
})

watch(() => props.isShowForm, (current) => {
  if (current) {
    state.roleForm = {
      ...state.roleForm,
      ...props.roleItem
    }
  }
})

const handelSubmit = () => {
  roleForm.value.validate(async (valid) => {
    console.log('submit: ', state.roleForm)
    try {
      if (!valid) {
        return
      }
      let str = ''
      const params = {
        action: props.action,
        ...state.roleForm,
      }
      await roleSubmit(params)
      if (props.action === 'add') {
        // console.log('create')
        str = `添加成功`
      } else if (props.action === 'edit') {
        console.log('edit')
        str = `修改成功`
      }
      ElMessage({
        message: str,
        type: 'success'
      })
      emits('closed')
    } catch (error) {
      console.error(error)
    }

  })
}

const handelClosed = () => {
  emits('closed')
  state.roleForm = {
    roleName: '',
    remark: ''
  }
}

</script>
<template>
  <el-dialog :title="props.action === 'add' ? '新增角色' : '修改角色'" :model-value="props.isShowForm" @closed="handelClosed">
    <el-form ref="roleForm" :model="state.roleForm" :rules="rules" label-width="100">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="state.roleForm.roleName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" rows="3" v-model="state.roleForm.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handelClosed">取消</el-button>
      <el-button @click="handelSubmit" type="primary">确定</el-button>
    </template>
  </el-dialog>
</template>